package com.tpc.client.systeme.core.datasource;

import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.smartgwt.client.data.fields.DataSourcePasswordField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Label;
import com.tpc.client.systeme.core.Systeme;
import com.tpc.client.systeme.core.service.AuthentificationService;
import com.tpc.client.systeme.core.service.AuthentificationServiceAsync;
import com.tpc.dao.extend.User;
import java.util.Date;

public class LoginDataSource extends GwtRpcDataSource {

    String strurl;
    Label labelChecking;

    public LoginDataSource(String strID) {
            setID(strID);
            
            DataSourceTextField dsfUsername = new DataSourceTextField("USERNAME", "Username", 320, Boolean.TRUE);
            DataSourcePasswordField dsfPassword = new DataSourcePasswordField("PASSWORD", "Password", 320, Boolean.TRUE);
            setFields(dsfUsername,dsfPassword);

            strurl = Page.getAppDir();
            strurl = strurl.substring(0,strurl.length()-1);
            strurl = strurl.substring(strurl.lastIndexOf("/"));
    }

    public void setObjects(Label labelParam) {
        labelChecking = labelParam;
    }

     @Override
    protected void executeFetch (final String requestId, final DSRequest request, final DSResponse response) {
       
    }

    @Override
    protected void executeAdd (final String requestId, final DSRequest request, final DSResponse response) {
   
    }

    @Override
    protected void executeUpdate (final String requestId, final DSRequest request, final DSResponse response) {
         JavaScriptObject jsoRequest = request.getData();
        Record requestInfo = new Record(jsoRequest);
        String strUsername = requestInfo.getAttribute("USERNAME");
        String strPassword = requestInfo.getAttribute("PASSWORD");
        AuthentificationServiceAsync service = (AuthentificationServiceAsync) GWT.create(AuthentificationService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        endpoint.setServiceEntryPoint(GWT.getModuleBaseURL()+"authenticator");
        service.validateLogin(strUsername,strPassword,new AsyncCallback<User> () {
            public void onFailure (Throwable caught) {
                response.setStatus (RPCResponse.STATUS_FAILURE);
                processResponse (requestId, response);
                labelChecking.setVisible(Boolean.FALSE);
            }
            public void onSuccess (User result) {
                response.setData(null);
                processResponse(requestId, response);
                if (result != null) {
                    Cookies.setCookie("krypton_userid",new Integer(result.getId()).toString());
                    Cookies.setCookie("krypton_username",result.getUsername());
                    Cookies.setCookie("krypton_username",result.getUsername());
                    Cookies.setCookie("krypton_firstname",result.getFirstName());
                    Cookies.setCookie("krypton_lastname",result.getLastName());
                    Cookies.setCookie("krypton_dictionary",result.getLangue().getCode());
                    Cookies.setCookie("krypton_group",new Integer(result.getGroupeDefaut()).toString());
                    Cookies.setCookie("krypton_isAdmin",result.getIsAdmin());
                    Cookies.setCookie("krypton_organisationname",result.getOrganisation().getName());
                    Cookies.setCookie("krypton_organisationid",new Integer(result.getOrganisation().getId()).toString());
                    Window.open(result.getLoginPath()+"?param="+new Date().getTime(),"_self",null);
                }
                else {
                    SC.say("ACCES INTERDIT! <br> Vérifiez votre nom d'usager et mot de passe.");
                }
                labelChecking.setVisible(Boolean.FALSE);
            }
        });
    }

    @Override
    protected void executeRemove (final String requestId, final DSRequest request, final DSResponse response) {
         //@TODO : fdsa
    }

    public void logout(final Systeme systeme) {
        AuthentificationServiceAsync service = (AuthentificationServiceAsync) GWT.create(AuthentificationService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;        
        endpoint.setServiceEntryPoint(systeme.getPageUrl()+"/com.tpc.authentification/authenticator");
        service.logout(new AsyncCallback<String> () {
            public void onFailure (Throwable caught) {
                SC.say("Failure");
            }
            public void onSuccess (String result) {
                Cookies.removeCookie("krypton_username");
                Cookies.removeCookie("krypton_firstname");
                Cookies.removeCookie("krypton_lastname");
                Cookies.removeCookie("krypton_dictionary");
                Cookies.removeCookie("krypton_group");
                Cookies.removeCookie("krypton_isAdmin");
                Cookies.removeCookie("krypton_organisation");
                Window.Location.assign(systeme.getPageUrl()+"/logout_buffer1.jsp");
            }
        });
    }

}